package com.sky.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.EmployeeUpdatePasswordDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @ApiOperation(value = "员工登录")
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     * @return
     */
    @ApiOperation(value = "新增员工")
    @PostMapping
    public Result save(@RequestBody EmployeeDTO employeeDTO) {
        employeeService.save(employeeDTO);
        return Result.success();
    }


    /**
     * 条件模糊分页查询显示员工列表
     * @param employeePageQueryDTO
     * @return
     */
    @GetMapping(value = "/page")
    @ApiOperation(value = "条件模糊分页查询显示员工列表")
    public Result pageQuery(EmployeePageQueryDTO employeePageQueryDTO){
        log.info("employeePageQueryDTO={}",employeePageQueryDTO);
        // 开始分页
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        // 分页条件查询
        List<Employee> employees = employeeService.pageQuery(employeePageQueryDTO);
        PageInfo<Employee> employeePageInfo = new PageInfo<>(employees);
        Long total = employeePageInfo.getTotal();   // 总记录数
        List<Employee> records = employeePageInfo.getList();    // 符合条件的记录
        PageResult pageResult = new PageResult(total, records);
        return Result.success(pageResult);
    }

    /**
     * 启用或禁用员工账号
     * @param status
     * @param id
     * @return
     */
    @ApiOperation(value = "启用或禁用员工账号")
    @PostMapping(value = "/status/{status}")
    public Result startOrStop(@PathVariable(value = "status") Integer status,Integer id){
        employeeService.startOrStop(status,id);
        return Result.success();
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询员工信息")
    @GetMapping(value = "{id}")
    public Result<Employee> getById(@PathVariable(value = "id") Long id){
        Employee employee = employeeService.getById(id);
        return Result.success(employee);
    }

    /**
     * 编辑员工信息
     * @return
     */
    @PutMapping
    @ApiOperation(value = "编辑员工信息")
    public Result updateEmployee(@RequestBody EmployeeDTO employeeDTO){
        employeeService.updateEmployee(employeeDTO);
        return Result.success();
    }

    @PutMapping(value = "/editPassword")
    @ApiOperation(value = "修改员工密码")
    public Result updatePassword(@RequestBody EmployeeUpdatePasswordDTO employeeUpdatePasswordDTO){
        // 由于前端并没有将该员工id当作数据返回给后端，所以此处从拦截器中将放置在ThreadLocal中的该员工id取出
        Long empId = BaseContext.getCurrentId();
        Employee employee = employeeService.getById(empId);
        String oldPassword = employee.getPassword();    // 取出当前员工的原密码
        // 判断员工输入的旧密码是否和数据库中的相同
        if(!DigestUtils.md5DigestAsHex(employeeUpdatePasswordDTO.getOldPassword().getBytes()).equals(oldPassword)){
            // 不相同
            return Result.error(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        employeeUpdatePasswordDTO.setEmpId(empId);
        employeeService.updateEmployee(employeeUpdatePasswordDTO);
        return Result.success();
    }
}
